<template>
  <div class="novel-management-container">
    <h2>小说管理</h2>
    <div class="toolbar">
      <app-search @search="performSearch" placeholder="按小说名搜索" />
      <el-button type="primary" @click="openNovelDialog()">添加小说</el-button>
    </div>
    <el-table :data="data" v-loading="loading">
      <el-table-column prop="novel_id" label="ID" />
      <el-table-column prop="novel_name" label="书名" />
      <el-table-column prop="author_id" label="作者ID" />
      <el-table-column prop="category" label="分类" />
      <el-table-column prop="status" label="状态" />
      <el-table-column label="操作" width="280">
        <template #default="{ row }">
          <el-button size="small" @click="openNovelDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button size="small" @click="openCommentsDialog(row)">管理评论</el-button>
          <el-button size="small" :type="row.status === 'published' ? 'warning' : 'success'" @click="toggleNovelStatus(row)">
            {{ row.status === 'published' ? '下架' : '上架' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <app-pagination
      v-model:current-page="pagination.currentPage"
      v-model:page-size="pagination.pageSize"
      :total="pagination.total"
      @update:current-page="handlePageChange"
      @update:page-size="handleSizeChange"
    />

    <!-- Novel Edit/Create Dialog -->
    <el-dialog v-model="novelDialogVisible" :title="isEditMode ? '编辑小说' : '添加小说'">
      <el-form :model="novelForm" ref="novelFormRef" label-width="80px">
        <el-form-item label="书名" prop="novel_name">
          <el-input v-model="novelForm.novel_name" />
        </el-form-item>
        <el-form-item label="作者ID" prop="author_id">
          <el-input v-model="novelForm.author_id" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-input v-model="novelForm.category" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="novelForm.status">
            <el-option label="连载中" value="连载中" />
            <el-option label="已完结" value="已完结" />
            <el-option label="已下架" value="已下架" />
          </el-select>
        </el-form-item>
        <el-form-item label="章节数" prop="chapter_count">
          <el-input-number v-model="novelForm.chapter_count" :min="0" />
        </el-form-item>
        <el-form-item label="简介" prop="review">
          <el-input v-model="novelForm.review" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="novelDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveNovel">保存</el-button>
      </template>
    </el-dialog>

    <!-- Comments Dialog -->
    <el-dialog v-model="commentsDialogVisible" title="管理评论" width="70%">
      <comment-management v-if="selectedNovelId" :novel-id="selectedNovelId" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useCRUD } from '@/composables/useCRUD'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'
import AppSearch from '@/components/AppSearch.vue'
import AppPagination from '@/components/AppPagination.vue'
import CommentManagement from '@/components/CommentManagement.vue'

const { 
  data, 
  loading, 
  pagination, 
  fetchData, 
  handleSearch, 
  handlePageChange, 
  handleSizeChange 
} = useCRUD('/admin/novels')

const novelDialogVisible = ref(false)
const novelFormRef = ref(null)
const novelForm = reactive({
  novel_id: null,
  novel_name: '',
  author_id: '',
  category: '',
  status: '连载中',
  chapter_count: 0,
  review: ''
})

const isEditMode = computed(() => !!novelForm.novel_id)

const commentsDialogVisible = ref(false)
const selectedNovelId = ref(null)

const performSearch = (query) => {
  handleSearch({ q: query })
}

const openNovelDialog = (novel) => {
  if (novel && novel.novel_id) {
    Object.assign(novelForm, novel)
  } else {
    Object.assign(novelForm, {
      novel_id: null, novel_name: '', author_id: '', category: '',
      status: '连载中', chapter_count: 0, review: ''
    })
  }
  novelDialogVisible.value = true
}

const saveNovel = async () => {
  try {
    if (isEditMode.value) {
      await request.put(`/admin/novels/${novelForm.novel_id}`, novelForm)
      ElMessage.success('小说更新成功')
    } else {
      await request.post('/admin/novels', novelForm)
      ElMessage.success('小说添加成功')
    }
    novelDialogVisible.value = false
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleDelete = (novel) => {
  ElMessageBox.confirm(`确定要删除《${novel.novel_name}》吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await request.delete(`/admin/novels/${novel.novel_id}`)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const openCommentsDialog = (novel) => {
  selectedNovelId.value = novel.novel_id
  commentsDialogVisible.value = true
}

const toggleNovelStatus = async (novel) => {
  const newStatus = novel.status === 'published' ? 'unpublished' : 'published';
  try {
    await request.patch(`/admin/novels/${novel.novel_id}/status`, { status: newStatus })
    ElMessage.success('状态更新成功')
    fetchData()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}
</script>

<style scoped>
.novel-management-container {
  padding: 20px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>